package com.woniushop.web.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.woniushop.entity.OrderForm;
import com.woniushop.entity.OrderInfo;
import com.woniushop.entity.PageBean;
import com.woniushop.entity.User;
import com.woniushop.service.OrderFormService;
import com.woniushop.service.OrderInfoService;
import com.woniushop.service.imple.OrderFormServiceImple;
import com.woniushop.service.imple.OrderInfoServiceImple;
import com.woniushop.utils.ControllerUtils;

/**
 * Servlet implementation class OrderFormServlet
 */
@WebServlet("/orderForm")
public class OrderFormServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private OrderFormService orderFormService = new OrderFormServiceImple();
	private OrderInfoService orderInfoService = new OrderInfoServiceImple();

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String opr = request.getParameter("opr");
		switch (opr) {
		case "buyNow":// 立即购买
			buyNow(request, response);
			break;
		case "cancelOrder":// 取消（删除）订单F
			cancelOrder(request, response);
			break;
		case "orderFromCart":// 将购物车中的商品提交为新订单
			orderFromCart(request, response);
			break;
		case "findValidByPage":// 查询用户的所有有效订单
			findValidByPage(request, response);
			break;
		case "toPay":// 订单继续支付
			toPay(request, response);
			break;
		case "receipt":// 确认收货
			receipt(request, response);
			break;
		case "pay":// 确认支付
			pay(request, response);
			break;
		case "deliver":// 后台发货
			deliver(request, response);
			break;
		default:
			break;
		}
	}

	private void deliver(HttpServletRequest request, HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 获得登录用户
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			if (loginUser == null || loginUser.getUstate() == 2 || loginUser.getUrole() == 3) {
				request.setAttribute("msg", "null");
			} else {
				Integer oid = Integer.parseInt(request.getParameter("oid"));

				// 确认收货
				orderFormService.deliver(oid);

				map.put("msg", "ok");
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);		
	}

	private void pay(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 获得登录用户
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			if (loginUser == null || loginUser.getUstate() == 2 || loginUser.getUrole() != 3) {
				request.setAttribute("msg", "null");
			} else {
				// 将订单详情从session中移除
				request.getSession().removeAttribute("list");
				// 获得订单
				OrderForm orderForm = (OrderForm) request.getSession().getAttribute("orderForm");
				// 将订单从session中移除
				request.getSession().removeAttribute("orderForm");
				// 设置订单地址
				Integer aid = Integer.parseInt(request.getParameter("aid"));
				orderForm.setAid(aid);
				orderFormService.pay(orderForm);

				// 将订单总价从session中移除
				request.getSession().removeAttribute("totalPrice");
				map.put("msg", "ok");
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	private void receipt(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 获得登录用户
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			if (loginUser == null || loginUser.getUstate() == 2 || loginUser.getUrole() != 3) {
				request.setAttribute("msg", "null");
			} else {
				Integer oid = Integer.parseInt(request.getParameter("oid"));

				// 确认收货
				orderFormService.receipt(oid);

				map.put("msg", "ok");
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	private void toPay(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 获得登录用户
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			if (loginUser == null || loginUser.getUstate() == 2 || loginUser.getUrole() != 3) {
				request.setAttribute("msg", "null");
			} else {
				Integer oid = Integer.parseInt(request.getParameter("oid"));
				// 获得订单
				OrderForm orderForm = orderFormService.findOne(oid);

				// 获得订单明细
				List<OrderInfo> list = orderInfoService.findAll(oid);

				// 计算商品总价
				BigDecimal totalPrice = new BigDecimal(0);
				for (OrderInfo orderInfo : list) {
					BigDecimal num = new BigDecimal(orderInfo.getOinum());
					totalPrice = totalPrice.add(orderInfo.getGprice().multiply(num));
				}

				// 将订单、订单明细、商品总价发往支付页面
				map.put("msg", "ok");
				request.getSession().setAttribute("orderForm", orderForm);
				request.getSession().setAttribute("list", list);
				request.getSession().setAttribute("totalPrice", totalPrice);
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	private void findValidByPage(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 获得登录用户
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			if (loginUser == null || loginUser.getUstate() == 2) {
				map.put("msg", "null");
			} else {
				// 创建pageBean
				PageBean pageBean = new PageBean();

				// 获得页码，如果没有页码，则设置页码为1
				String page = request.getParameter("page");
				if (page == null || page.trim().length() == 0 || Integer.parseInt(page) < 1) {
					pageBean.setPage(1);
				} else {
					pageBean.setPage(Integer.parseInt(page));
				}

				// 设置分页大小
				pageBean.setPageSize(5);

				// 设置查询条件
				OrderForm orderForm = new OrderForm();
				if (loginUser.getUrole() == 3) {
					orderForm.setUid(loginUser.getUid());
				}
				Integer ostate = Integer.parseInt(request.getParameter("ostate"));
				orderForm.setOstate(ostate);// ostate==0表示查询所有非购物车订单

				// 获得分页数据
				List<OrderForm> list = orderFormService.findValidByPage(pageBean, orderForm);
				map.put("list", list);
				map.put("pageBean", pageBean);
				map.put("msg", "ok");
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	private void orderFromCart(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 获得登录用户
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			if (loginUser == null || loginUser.getUstate() == 2 || loginUser.getUrole() != 3) {
				request.setAttribute("msg", "null");
			} else {
				// 生成订单
				OrderForm orderForm = orderFormService.addNewOrder(loginUser.getUid());
				// 获得订单明细
				String[] oiids = request.getParameterValues("oiids[]");
				Integer oid = orderForm.getOid();
				orderInfoService.toOrder(oiids, oid);

				List<OrderInfo> list = orderInfoService.findAll(oid);

				// 计算商品总价
				BigDecimal totalPrice = new BigDecimal(0);
				for (OrderInfo orderInfo : list) {
					BigDecimal num = new BigDecimal(orderInfo.getOinum());
					totalPrice = totalPrice.add(orderInfo.getGprice().multiply(num));
				}

				// 将订单、订单明细、商品总价发往支付页面
				map.put("msg", "ok");
				request.getSession().setAttribute("orderForm", orderForm);
				request.getSession().setAttribute("list", list);
				request.getSession().setAttribute("totalPrice", totalPrice);
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	private void cancelOrder(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 获得登录用户
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			if (loginUser == null || loginUser.getUstate() == 2 || loginUser.getUrole() != 3) {
				request.setAttribute("msg", "null");
			} else {
				String oidStr = request.getParameter("oid");
				if (oidStr == null || oidStr.length() == 0) {
					// 获得当前订单详情
					@SuppressWarnings("unchecked")
					List<OrderInfo> list = (List<OrderInfo>) request.getSession().getAttribute("list");
					// 获得所有订单详情id；
					String[] oiids = new String[list.size()];
					for (int i = 0; i < oiids.length; i++) {
						oiids[i] = list.get(i).getOiid() + "";
					}
					// 将订单详情从session中移除
					request.getSession().removeAttribute("list");
					// 删除所有订单详情
					orderInfoService.delAll(oiids);

					// 获得订单
					OrderForm orderForm = (OrderForm) request.getSession().getAttribute("orderForm");
					// 将订单从session中移除
					request.getSession().removeAttribute("orderForm");
					// 删除订单
					Integer oid = orderForm.getOid();
					orderFormService.del(oid);

					// 将订单总价从session中移除
					request.getSession().removeAttribute("totalPrice");
				} else {
					Integer oid = Integer.parseInt(oidStr);
					orderInfoService.deleteByOid(oid);
					orderFormService.del(oid);
				}
				map.put("msg", "ok");
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);

	}

	/**
	 * 立即购买
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void buyNow(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 获得登录用户
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			if (loginUser == null || loginUser.getUstate() == 2 || loginUser.getUrole() != 3) {
				request.setAttribute("msg", "null");
			} else {
				// 生成订单
				OrderForm orderForm = orderFormService.addNewOrder(loginUser.getUid());
				// 生成订单明细
				Integer gid = Integer.parseInt(request.getParameter("gid"));
				Integer oinum = Integer.parseInt(request.getParameter("oinum"));
				OrderInfo orderInfo = new OrderInfo();
				orderInfo.setGid(gid);
				if (oinum == null || oinum < 1) {
					oinum = 1;
				}
				orderInfo.setOinum(oinum);
				orderInfo.setOid(orderForm.getOid());

				orderInfo = orderInfoService.addNewOrderInfo(orderInfo);
				List<OrderInfo> list = new ArrayList<OrderInfo>();
				list.add(orderInfo);

				// 计算商品总价
				BigDecimal num = new BigDecimal(orderInfo.getOinum());
				BigDecimal totalPrice = orderInfo.getGprice().multiply(num);

				// 将订单、订单明细、商品总价发往支付页面
				map.put("msg", "ok");
				request.getSession().setAttribute("orderForm", orderForm);
				request.getSession().setAttribute("list", list);
				request.getSession().setAttribute("totalPrice", totalPrice);
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
